String.prototype.format = function() {
    var content = this;
    for (var i = 0; i < arguments.length; i++) {
        var replacement = '{' + i + '}';
        content = content.replace(replacement, arguments[i]);
    }
    return content;
};

var App = {
    init: function () {

        var global = {
            Views: App.Views,
            Cache: App.Cache
        };

        pager.extendWithPage(global);
        ko.applyBindings(global);
        pager.start();
    },
    Cache:
    {
        selectedPasajes : {
            origen: {},
            vuelta: {}
        },
        terminalesList: ko.observableArray([])
    },
    Views: {
        LastVmOpened: ko.observable(""),
        currentPageSize: ko.computed(function () {
        }, this)
    },
    Models: {
        Pasajes : {
            /*** Model utilizado para los params de la busqueda del pasaje ***/
            BuscarPasaje : function(param)
            {
                this.origen = ko.observable(param.origen);
                this.destino = ko.observable(param.destino);            
                this.fechaIda = ko.observable(param.fechaIda);
                this.fechaVuelta = ko.observable(param.fechaVuelta);
                this.pasajeros = ko.observable(param.pasajeros);
                this.IsOneWay  = ko.observable(param.IsOneWay);

                this.origenId = ko.computed(function() {
                 var obj = _.findWhere(App.Cache.terminalesList(), {Descripcion: this.origen() });
                 return (_.isEmpty(obj) == false) ? obj.IdParada : 0; 
             }, this);

                this.destinoId = ko.computed(function() {
                 var obj = _.findWhere(App.Cache.terminalesList(), {Descripcion: this.destino() });
                 return (_.isEmpty(obj) == false) ? obj.IdParada : 0; 
             }, this);
            }
        }
    },
    Common: {
        User:
        {
            userIsAuthenticated: "",
            userEmail: "",
            userPassword: ""
        },
        Config: {
            pageSizeMax: 20,
            lenguage: "English",
            toggleAnimationTime: 750,
            loadMaskMessage: "Loading...",
            usaStatesList: {},
            minCommentCharacter: 20,
            mixCommentCharacter: 100
        },
        UI: {
            Images: {
            },
            Icons: {
                Add: "",
                Save: "",
                Edit: "",
                Remove: "",
                Find: "",
                Refresh: ""
            },
            Titles: {
                add: "Add",
                save: "Save",
                edit: "Edit",
                remove: "Delete",
                find: "Find",
                refresh: "Refresh",
                confirm: "Confirm",
                info: "Info",
                warning: "Warning",
                error: "Error",
                description: "Descriptión"
            },
            Messages: {
                error: "There has been a system error. Please try your request again.",
                noDataFound: "No se encontraron coincidencias para la busqueda realizada.",
                rowNoSelected: "No se ha seleccionado ningun registro.",
                confirm: "¿ Desea confirmar la operacion ?"
            },
            Validation: {
                zipCodeMaxLength: 5,
                onlyNumbersAndIsRequired: {
                    required: true,
                    number: true
                }
            }
        },
        Aux: {
            getURIparams: function () {
                return JSON.parse('{"' + decodeURIComponent(window.location.href.split('?')[1].replace(/&/g, "\",\"").replace(/=/g, "\":\"").replace(/\+/g, ' ')) + '"}');
            },
            getVM: function (idView) {
                return function (callback) {

                    $.getScript("../../Scripts/views/" + idView + ".js", function (data, textStatus, jqxhr) {
                        var vm = new App.Views[idView]();
                        App.Views.LastVmOpened(idView);
                        vm.init();
                        callback(vm);
                    });
                };
            },
            dpickerInit: function (params) {
                var nowTemp = new Date();
                var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);


                var checkin = $('#' + params.id).datepicker({
                    onRender: function (date) {
                        return date.valueOf() < now.valueOf() ? 'disabled' : '';
                    }
                }).on('changeDate', function (ev) {
                    if (ev.date.valueOf() > checkout.date.valueOf()) {
                        var newDate = new Date(ev.date)
                        newDate.setDate(newDate.getDate() + 1);
                        checkout.setValue(newDate);
                    }
                    checkin.hide();
                    $("#" + ev.currentTarget.id).find(':input').trigger('change');

                }).data('datepicker');

                var checkout = $('#' + params.validateWith).datepicker({
                    onRender: function (date) {
                        return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
                    }
                }).on('changeDate', function (ev) {
                    checkout.hide();
                    $("#" + ev.currentTarget.id).find(':input').trigger('change');
                }).data('datepicker');


            },
            typeAheadTerminalesInit: function (typeAheadArray) {
                App.Common.Aux.getTerminalesList(function (data) {

                    $.each(typeAheadArray, function( index, value ) {

                       $('#' + value).typeahead({
                        name: 'terminales',
                        local: _.pluck(data, "Descripcion")
                    });

                   });
                });
            },
            formInputCleaner: function (Element) {
                $("#" + Element).find(':input').each(function () {
                    switch (this.type) {
                        case 'password':
                        case 'select-multiple':
                        case 'select-one':
                        case 'text':
                        case 'textarea':
                        $(this).val('');
                        break;
                        case 'checkbox':
                        case 'radio':
                        this.checked = false;
                    }
                });
            },
            disposeWorkingPlace: function (callBack) {
                $("#div_" + App.Views.LastVmOpened).toggle("explode", {}, App.Common.Configuration.ToggleAnimationTime, function () {

                    $('#div_Container').empty();

                    if (App.Views[App.Views.LastVmOpened] != null) {
                        App.Views[App.Views.LastVmOpened] = null;
                        App.Views.LastVmOpened = "";
                    }
                    callBack();
                });

            },
            wizardTbarSetActiveStep: function (newActiveStepId) {
                var fatherNode = $("#" + newActiveStepId).parent().parent().children();

                fatherNode.removeClass();

                fatherNode.each(function (Index) {
                    var idStep = $(this).children().attr("Id");

                    if (idStep == newActiveStepId) {
                        $(this).addClass('active-step');
                        return false;
                    } else {
                        $(this).addClass('completed-step');
                    }
                });
            },
            getTerminalByName: function (params) {
                var terminal = {};

                $.each(params.terminalesList, function (index, item) {
                    if (item.Descripcion == params.nameToFind) {
                        terminal = item;
                        return null;
                    }
                });

                return terminal;
            },
            getTerminalesList: function (callBack) {
                if (!$.isEmptyObject(App.Cache.terminalesList())) {
                    callBack(App.Cache.terminalesList());
                }
                else {

                    $.ajax({
                        url: "/Terminales/",
                        type: "GET",
                        success: function (Response) {
                            if (Response.success == true) {
                                if (Response.results > 0) {

                                    App.Cache.terminalesList(Response.data);
                                    callBack(Response.data);
                                }
                            }
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                        }
                    });

                }
            },
            shortTerminalName: function(name) {
                return name.slice(0, name.indexOf('('));
            },
            isExtraSmallView: function()
            {
                return $(window).width() < 768 ? true : false;
            }
        }
    }
};




ko.bindingHandlers.typeAheadValue = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
       $(element).off("focusout").focusout(function() {
        allBindingsAccessor().value($(element).val());
    })
   }};